package com.iqiyi.pps.epg.web.webapp.action.admin;

import com.iqiyi.pps.epg.core.rpc.qipu.QipuService;
import com.iqiyi.pps.epg.web.model.ValueNode;
import com.iqiyi.pps.epg.web.service.zk.*;
import com.iqiyi.pps.epg.web.utils.Struts2Utils;
import com.iqiyi.pps.epg.web.model.ZTree;
import com.opensymphony.xwork2.ActionSupport;
import org.apache.commons.lang.StringUtils;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;

import java.io.IOException;
import java.util.Set;

/**
 * User: rainliang
 * Mail: rainliang@qiyi.com
 * Date: 2014/7/7
 * Time: 15:52
 * Desc:
 */
@Namespace("/admin/zk")
@Scope("prototype")
public class ZookpeerAction extends ActionSupport {

    @Autowired
    private ZkOptionService zkOptionService;
    @Autowired
    private QipuService qipuService;


    private String patch;
    private String zpath;
    private String connectStr;

    @Action("getNodeData")
    public void getNodeData(){
        try {
            ZookeeperConnection connection = getConnection();
            connection.setConnectString(connectStr);
            ValueNode vn = zkOptionService.getValueNode(zpath, connection);
            ZTree zTree = ConvertTreeNode.convertValueNode(vn);

            Struts2Utils.renderJson(zTree);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Action("getPathData")
    public void showTreeData() {
        try {
            ZookeeperConnection connection = getConnection();
            connection.setConnectString(connectStr);
            ValueNode vn = zkOptionService.getValueNode(zpath, connection);
            ZTree zTree = ConvertTreeNode.convertValueNode(vn);
            String json = Bean2ViewUtil.cvtTreeChilds2Json(zTree);
            Struts2Utils.renderJson(json);

        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    @Action("removeZKNode")
    public String removeZKNode(){

        try {
            if ("/".equals(zpath)) {
                Set connSet = null;
//                removeConnSet(request, connectStr);
                Struts2Utils.renderJson("{\"result\":1}");
                return null;
            }
            ZookeeperConnection connection = getConnection();
            connection.setConnectString(connectStr);
            boolean result = zkOptionService.deletePath(zpath, connection);

            if (result) {
                Struts2Utils.renderJson("{\"result\":1}");
            } else {
                Struts2Utils.renderJson("{\"result\":0}");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    private String nodeName;
    private String nodeValue;

    @Action("addZKNode")
    public String addZKNode() {
        try {
            ZookeeperConnection connection = getConnection();
            connection.setConnectString(connectStr);
            String path = zkOptionService.createPath(zpath + ("/".equals(zpath) ? "" : "/") + nodeName, nodeValue.getBytes(), connection);

            if (StringUtils.isNotEmpty(path)) {
                ValueNode vn = zkOptionService.getValueNode(zpath + "/" + nodeName, connection);
                ZTree zTree = ConvertTreeNode.convertValueNode(vn);
                String json = Bean2ViewUtil.cvtTree2Json(zTree);
                Struts2Utils.renderJson("{\"result\":1,\"node\":" + json + "}");
            } else {
                Struts2Utils.renderJson("{\"result\":0}");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @Action("addRootNode")
    public void addRootNode() {
        try {
            Set connSet = createConnSet(connectStr);
            Struts2Utils.renderJson("{\"result\":1,\"rootNodes\":" + Bean2ViewUtil.convert2RootNodes(connSet) + "}");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private Set createConnSet(String connectStr) throws IOException {
        Set<String> connSet = (Set<String>) JSONFile.readConnects();
        if (StringUtils.isNotEmpty(connectStr) && !connSet.contains(connectStr)) {
            connSet.add(connectStr);
            JSONFile.persistConnect(connSet);
        }

        return connSet;
    }

    private String content;

    @Action("modifyNode")
    public void modifyNode() throws IOException {
        ZookeeperConnection connection = getConnection();
        connection.setConnectString(connectStr);

        boolean result = zkOptionService.setData(connection, zpath, content);

        if (result) {
            Struts2Utils.renderJson("{\"result\":1}");
        } else {
            Struts2Utils.renderJson("{\"result\":0}");
        }
    }

    @Action(value = "zk", results = {@Result(name = SUCCESS, location = "/WEB-INF/content/admin/zk/zk.jsp")})
    public String show(){
        try {
            Set connSet = null;
            connSet = createConnSet(connectStr);
            Struts2Utils.getRequest().setAttribute("rootNodes", Bean2ViewUtil.convert2RootNodes(connSet));
        } catch (IOException e) {
            e.printStackTrace();
        }

        return SUCCESS;
    }

    public ZookeeperConnection getConnection() {
        ZookeeperConnection connection;
        connection = new ZookeeperConnection();
//        connection.setSessionTimeout(30000);
        connection.setWatcher(new EventWatcher());
        return connection;
    }

    public String getPatch() {
        return patch;
    }

    public void setPatch(String patch) {
        this.patch = patch;
    }

    public String getZpath() {
        return zpath;
    }

    public void setZpath(String zpath) {
        this.zpath = zpath;
    }

    public String getConnectStr() {
        return connectStr;
    }

    public void setConnectStr(String connectStr) {
        this.connectStr = connectStr;
    }
}
